package vn.appsmobi.ui;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import vn.appsmobi.R;
import vn.appsmobi.adapter.AppInstalledAdapter;
import vn.appsmobi.model.AppInfo;
import vn.appsmobi.model.LocalAppInfo;
import vn.appsmobi.ulti.LocalAppManager;
import vn.appsmobi.ulti.Log;
import vn.appsmobi.ulti.MemoryStatus;
import vn.appsmobi.widget.SearchBar;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.IPackageStatsObserver;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.PackageStats;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.RemoteException;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;


public class LocalAppFragment extends BaseFragment implements OnClickListener
{
	
	View linear_sd;
	View linear_internal;
	ProgressBar progressbar_interal;
	ProgressBar progressbar_sd;
	TextView txt_sd;
	TextView txt_internal;
	AppInstalledAdapter mAdapter;
	ListView mAppsList;
	SearchBar mSearchBar;
	private ArrayList<AppInfo> mApps;
	Method getPackageSizeInfo = null;
	/**Phong
	 * 
	 */
	public LocalAppFragment() {
		super();
		// TODO Auto-generated constructor stub
	}

	/* (non-Javadoc)
	 * @see android.support.v4.app.Fragment#onActivityCreated(android.os.Bundle)
	 */
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
	}

	/* (non-Javadoc)
	 * @see android.support.v4.app.Fragment#onCreate(android.os.Bundle)
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		//
		
	}

	/* (non-Javadoc)
	 * @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
	 */
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// 
		ArrayList<LocalAppInfo> mApps = LocalAppManager.getManager().getInstalledApp(); 
		
	
		Log.v(""+mApps.size());
		View view = inflater.inflate(R.layout.fragment_localapp, container, false);
		
		this.mSearchBar 	= (SearchBar) view.findViewById(R.id.searchBar);
		this.mSearchBar.setTextHint(String.format(LocalAppFragment.this. getActivity().getString(R.string.search_in_string),mApps.size()));
		this.mSearchBar.addTextChangedListener(new TextWatcher() {
		     
		    @Override
		    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
		        // When user changed the Text
		    	LocalAppFragment.this.mAdapter.getFilter().filter(cs);   
		    }
		     
		    @Override
		    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
		            int arg3) {
		        // TODO Auto-generated method stub
		         
		    }
		     
		    @Override
		    public void afterTextChanged(Editable arg0) {
		        // TODO Auto-generated method stub                          
		    }
		});
		
		this.linear_internal = view.findViewById(R.id.linear_internal);
		this.linear_sd = view.findViewById(R.id.linear_sd);
		this.progressbar_interal = (ProgressBar) view.findViewById(R.id.progressbar_internal);
		this.progressbar_sd = (ProgressBar) view.findViewById(R.id.progressbar_sd);
		this.txt_internal 	= (TextView) view.findViewById(R.id.txt_internal);
		this.txt_sd 	= (TextView) view.findViewById(R.id.txt_sd);
		long memory_sd_total = 0;
		long memory_sd_free = 0;
		long memory_internal_total = 0;
		long memory_internal_free = 0;
		
		if(MemoryStatus.externalMemoryAvailable() == false)
		{
			this.linear_sd.setVisibility(View.GONE);			
		}
		else
		{
			memory_sd_total = MemoryStatus.getTotalExternalMemorySize()/1024/1024;
			memory_sd_free 	= MemoryStatus.getAvailableExternalMemorySize()/1024/1024;
			this.progressbar_sd.setMax((int) memory_sd_total);
			this.progressbar_sd.setProgress((int) (memory_sd_free) );
			this.progressbar_sd.setContentDescription("" + memory_sd_free + " MB trống /" + memory_sd_total + " MB" );
			this.txt_sd.setText("" + memory_sd_free + " MB trống /" + memory_sd_total + " MB" ); 
		}
		
		memory_internal_total 	= MemoryStatus.getTotalInternalMemorySize()/1024/1024;
		memory_internal_free 	= MemoryStatus.getAvailableInternalMemorySize()/1024/1024;
		
		this.progressbar_interal.setMax((int) memory_internal_total);
		this.progressbar_interal.setProgress((int) (memory_internal_free) );
		this.progressbar_interal.setContentDescription("" + memory_internal_free + " MB trống /" + memory_internal_total + " MB" );
		this.txt_internal.setText("" + memory_internal_free + " MB trống /" + memory_internal_total + " MB" ); 
		
		mAppsList = (ListView) view.findViewById(R.id.listInstalledApp);	     	   
	      
      mAdapter = new AppInstalledAdapter(this.getActivity());
      mAdapter.setListItems(mApps);
      mAppsList.setAdapter(mAdapter);
      
      new LoadIconsTask().execute(mApps.toArray(new AppInfo[]{}));
		
		
		
		return view;
	}

	
	 private ArrayList<AppInfo> loadInstalledApps(boolean includeSysApps) {
		  ArrayList<AppInfo> apps = new ArrayList<AppInfo>();
	      
	      // the package manager contains the information about all installed apps
	      PackageManager packageManager = this.getActivity().getPackageManager();
	      try {
	          getPackageSizeInfo = packageManager.getClass().getMethod("getPackageSizeInfo", String.class, IPackageStatsObserver.class);
	      } catch (SecurityException e1) {

	          e1.printStackTrace();
	      } catch (NoSuchMethodException e1) {

	          e1.printStackTrace();
	      } 
	      List<PackageInfo> packs = packageManager.getInstalledPackages(0); //PackageManager.GET_META_DATA 
	      
	      for(int i=0; i < packs.size(); i++) {
	         PackageInfo p = packs.get(i);
	         ApplicationInfo a = p.applicationInfo;
	         // skip system apps if they shall not be included
	         if ((!includeSysApps) && ((a.flags & ApplicationInfo.FLAG_SYSTEM) == 1)) {
	            continue;
	         }
	         final AppInfo app = new AppInfo();
	         app.setName(p.applicationInfo.loadLabel(packageManager).toString());
	         app.setPackageName(p.packageName);
	         app.setVersion(p.versionName);	 
	         
	         CharSequence description = p.applicationInfo.loadDescription(packageManager);
	         app.setDescription(description != null ? description.toString() : "");
	         
	         try {
                 getPackageSizeInfo.invoke(packageManager,  p.packageName, new IPackageStatsObserver.Stub()  {

                   public void onGetStatsCompleted(PackageStats pStats, boolean succeeded) throws RemoteException {
                	   			Log.v("apksize "+ pStats.codeSize/1024.0/1024.0);
                                  app.setSize((float) (pStats.codeSize/1024.0/1024.0));
                   }           
           });
               }catch(IllegalAccessException e) {}
               catch(IllegalArgumentException r) {}
               catch(InvocationTargetException w){}
	         
	         
	         apps.add(app);
	      }
	      return apps;
	   }
	 
	 /**
	    * An asynchronous task to load the icons of the installed applications.
	    */
	   private class LoadIconsTask extends AsyncTask<AppInfo, Void, Void> {
	      @Override
	      protected Void doInBackground(AppInfo... apps) {
	         
	         Map<String, Drawable> icons = new HashMap<String, Drawable>();
	         PackageManager manager = LocalAppFragment.this.getActivity().getPackageManager();
	         
	         for (AppInfo app : apps) {
	            String pkgName = app.getPackageName();
	            Drawable ico = null;
	            try {
	               Intent i = manager.getLaunchIntentForPackage(pkgName);
	               if (i != null) {
	                  ico = manager.getActivityIcon(i);	         
	               }
	            } catch (NameNotFoundException e) {
	               Log.v("ERROR Unable to find icon for package '" + pkgName + "': " + e.getMessage());
	            }
	            icons.put(app.getPackageName(), ico);
	         }
	         mAdapter.setIcons(icons);
	         
	         return null;
	      }
	      
	      @Override
	      protected void onPostExecute(Void result) {
	         mAdapter.notifyDataSetChanged();
	      }
	  }

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
	}
	
}
